﻿using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Identity;
using Volo.Abp.Security.Claims;

namespace Bridge.AuthServer.Host
{
    /// <summary>
    /// 自定义Claims
    /// </summary>
    public class CustomProfileService : IProfileService, ISingletonDependency
    {

        private readonly IdentityUserManager _userManager;
        public CustomProfileService(IdentityUserManager userManager)
        {
            _userManager = userManager;

        }
        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            //获得登录用户的ID
            var userId = context.Subject.GetSubjectId();
            var user = await _userManager.FindByIdAsync(userId);
            var roleNames = (await _userManager.GetRolesAsync(user)).ToList();

            //创建一个以当前用户为主体的凭证
            var claims = new List<Claim>();
            //自定义claims区间
            foreach (var kv in user.ExtraProperties)
            {
                claims.Add(new Claim(kv.Key, kv.Value?.ToString() ?? string.Empty));
            }




            claims.Add(new Claim(AbpClaimTypes.Name, user.Name ?? string.Empty));
            claims.Add(new Claim(AbpClaimTypes.UserName, user.UserName ?? string.Empty));
            claims.Add(new Claim(AbpClaimTypes.SurName, user.Surname ?? string.Empty));
            claims.Add(new Claim(AbpClaimTypes.PhoneNumber, user.PhoneNumber));
            claims.Add(new Claim(AbpClaimTypes.Email, user.Name ?? string.Empty));

            claims.Add(new Claim(AbpClaimTypes.TenantId, user.TenantId?.ToString() ?? string.Empty));

            roleNames.ForEach((role) => claims.Add(new Claim(AbpClaimTypes.Role, role)));




            //设置claims
            context.IssuedClaims = claims;

        }

        public async Task IsActiveAsync(IsActiveContext context)
        {
            var sub = context.Subject.GetSubjectId();
            var user = await _userManager.FindByIdAsync(sub);
            context.IsActive = user != null;
        }
    }
}
